package com.jzzzb.debug.registry;

import com.jzzzb.debug.annotation.MapperScan;
import com.jzzzb.debug.scanner.MapperBeanScanner;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;

import java.beans.Introspector;
import java.util.Map;

public class GenericBeanScanRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName());
		String path = (String) attributes.get("value");

		MapperBeanScanner mapperBeanScanner = new MapperBeanScanner(registry);
		mapperBeanScanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
		mapperBeanScanner.setBeanNameGenerator((definition, beanRegistry) -> {
			String className = definition.getBeanClassName();
			if (className != null) {
				return Introspector.decapitalize(ClassUtils.getShortName(className));
			}
			return null;
		});
		mapperBeanScanner.scan(path);
	}
}
